package red.yancloud.www.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.webkit.JavascriptInterface
import androidx.appcompat.widget.AppCompatTextView
import com.alibaba.fastjson.JSONObject
import com.example.zhouwei.library.CustomPopWindow
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_book_info.*
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import red.yancloud.www.R
import red.yancloud.www.base.BaseWebViewActivity
import red.yancloud.www.common.Constants
import red.yancloud.www.common.MessageEvent
import red.yancloud.www.db.sharedpreference.UserInfoShardPreference
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.BookEntity
import red.yancloud.www.internet.bean.BookInfo
import red.yancloud.www.internet.bean.Default
import red.yancloud.www.internet.bean.FavoriteState
import red.yancloud.www.manager.DatabaseManager
import red.yancloud.www.ui.read.EPupReadActivity
import red.yancloud.www.ui.read.PdfReadActivity
import red.yancloud.www.util.NetworkUtils
import red.yancloud.www.util.ToastUtils
import red.yancloud.www.util.UrlUtils

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/10 19:06
 * E_Mail：yh131412hys@163.com
 * Describe：书籍详情页面
 * Change：
 * @Version：V1.0
 */
class BookInfoActivity : BaseWebViewActivity(), View.OnClickListener {

    private val TAG = "BookInfoActivity"

    private lateinit var bookId:String
    private var bookBean: BookInfo.DataBean.BookBean? = null

    private var firstbookpdfurl:String = ""
    private var firstbookchapterid:String = ""
    private var bookcaseState:Int = -1
    private var id:String = ""
    private var state: Int = -1
    private var currentState: Int = -1

    override val layoutId: Int
        get() = R.layout.activity_book_info

    override fun initData() {
        super.initData()

        bookId = intent.getStringExtra("bookId")

        // 获取书籍信息
        // firstbookchapterid：-1 pdf 否则是epup的第一章 927
        getBookInfo()
    }
    private fun getBookInfo() {
        RedCloudApis.getInstance().bookInfo(UserInfoShardPreference.instance.uid, bookId, object : Observer<BookInfo> {
            override fun onComplete() {
            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: BookInfo) {

                if (t.code == Constants.SYSTEM_OK && t.data != null) {

                    bookBean = t.data.book
                    firstbookchapterid = t.data.book.firstbookchapterid
                    if (firstbookchapterid == Constants.BookType.PDF) {

                        firstbookpdfurl = t.data.book.firstbookpdfurl
                    }
                    bookcaseState = t.data.bookcaseState
                    //                    bookcaseState  1|0  1已经在书架，0书架没有
                    if (bookcaseState == 1 && !DatabaseManager.instance.checkBook(bookId)) {

                        val bookType: String
                        if (firstbookchapterid == Constants.BookType.PDF) {

                            bookType = Constants.BookType.PDF
                        }else{

                            bookType = Constants.BookType.E_PUP
                        }

//                        bookBean!!.lastchapter? bookBean!!.lastchapter可为空
                        DatabaseManager.instance.insertBookInfo(
                            BookEntity(bookBean!!.id.toLong(), bookBean!!.title, bookBean!!.thumbnail, bookBean!!.author,bookType,
                                bookBean!!.firstbookpdfurl,bookBean!!.firstbookchapterid,bookBean!!.lastchapter?.id,"0",0))
                    }
                }
            }

            override fun onError(e: Throwable) {
            }
        })
    }

    override fun configViews() {
        super.configViews()

        back_iv.setOnClickListener(this)
        bookInfoActivity_more_iv.setOnClickListener(this)
        bookInfoActivity_addBookStore_tv.setOnClickListener(this)
        bookInfoActivity_startRead_tv.setOnClickListener(this)

        webViewActivity_refreshLayout.setEnableLoadMore(false)
    }

    @SuppressLint("AddJavascriptInterface")
    override fun addJavaScriptInterface() {

        mWebView.addJavascriptInterface(object : Any() {

            @JavascriptInterface
            fun loadData(){

                mHandler.post(object :Runnable{
                    override fun run() {
                        mWebView.loadUrl("javascript:waves(" + UrlUtils.makeJsonText() + ")")
                        if (!isFinishing) {
                            loadingDialog.dismiss()
                        }
                    }
                })
            }

            @JavascriptInterface
            fun gotopage(key: String,value: String) {
                mHandler.post {
                    // 跳转书籍目录
                    if (key=="catalog") {

                        startActivity(Intent(this@BookInfoActivity,BookCatalogActivity::class.java)
                            .putExtra("bookId",bookId))
                    }
                }
            }

            @JavascriptInterface
            fun showbook(bookId: String) {
                mHandler.post {
                    // 跳转书籍详情
                    startActivity(Intent(this@BookInfoActivity, BookInfoActivity::class.java).putExtra("bookId",bookId)
                        .putExtra(
                            "url",
                            "${Constants.API_BASE_RED_CLOUD_URL}article/?bid=$bookId"
                        ))
                }
            }
        },"demo")
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.back_iv-> finish()
            R.id.bookInfoActivity_more_iv-> {

                if (!NetworkUtils.isConnected(mContext)) {
                    ToastUtils.toastNetErrorMsg()
                    return
                }

                if (UserInfoShardPreference.instance.isLogin) {

                    RedCloudApis.getInstance().getFavoriteState(UserInfoShardPreference.instance.uid,bookId,Constants.CollectModel.BOOK,object : Observer<FavoriteState> {
                        override fun onComplete() {
                        }

                        override fun onSubscribe(d: Disposable) {
                        }

                        override fun onNext(t: FavoriteState) {

                            if (t.code == Constants.SYSTEM_OK) {

                                if (t.data != null) {

                                    id = t.data.id
                                    state = Constants.CollectType.COLLECT
                                }else{

                                    state = Constants.CollectType.NOT_COLLECT
                                }

                                currentState = state
                                initPopupWindow(v)
                            }
                        }

                        override fun onError(e: Throwable) {

                            state = Constants.CollectType.NOT_COLLECT
                            currentState = state
                            initPopupWindow(v)
                        }
                    })
                }else{

                    state = Constants.CollectType.NOT_COLLECT
                    currentState = state
                    initPopupWindow(v)
                }
            }
            R.id.bookInfoActivity_addBookStore_tv -> {

                if (UserInfoShardPreference.instance.isLogin) {

//                    bookcaseState  1|0  1已经在书架，0书架没有
                    if (bookcaseState==0) {

                        RedCloudApis.getInstance().addBookcase(UserInfoShardPreference.instance.uid,bookId,firstbookchapterid,object : Observer<Default> {
                            override fun onComplete() {
                            }

                            override fun onSubscribe(d: Disposable) {
                            }

                            override fun onNext(t: Default) {

                                if (t.code == Constants.SYSTEM_OK) {

                                    val bookType: String
                                    if (firstbookchapterid == Constants.BookType.PDF) {

                                        bookType = Constants.BookType.PDF
                                        Log.d(TAG,"PDF:$bookType")
                                    }else{

                                        bookType = Constants.BookType.E_PUP
                                        Log.d(TAG,"E_PUP:$bookType")
                                    }

                                    val insertBookInfoResult = DatabaseManager.instance.insertBookInfo(
                                        BookEntity(bookBean!!.id.toLong(), bookBean!!.title, bookBean!!.thumbnail, bookBean!!.author,bookType,
                                            bookBean!!.firstbookpdfurl,bookBean!!.firstbookchapterid,bookBean!!.lastchapter.id,"0",0))
                                    if (insertBookInfoResult!=-1L) {

                                        ToastUtils.showToast("加入书架成功")
                                    }

                                    bookcaseState=1
                                }else{

                                    ToastUtils.showToast("加入书架失败")
                                }
                            }

                            override fun onError(e: Throwable) {
                            }
                        })
                    }else{

                        ToastUtils.showToast("已加入书架,请勿重复添加")
                    }
                }else{

                    ToastUtils.showToast(R.string.not_login_prompt)
                    startActivity(Intent(this,LoginActivity::class.java))
                }
            }
            R.id.bookInfoActivity_startRead_tv -> {

                if (firstbookchapterid==Constants.BookType.PDF) {

                    startActivity(Intent(mContext, PdfReadActivity::class.java).putExtra("bookId",bookId).putExtra("firstbookpdfurl",firstbookpdfurl).putExtra("title",bookBean!!.title).putExtra("content",bookBean!!.content))
                }else{

                    startActivity(Intent(mContext, EPupReadActivity::class.java).putExtra("bookId",bookId).putExtra("firstbookchapterid",firstbookchapterid))
                }
            }
        }
    }

    private fun initPopupWindow(v: View?) {

        val contentView =
            LayoutInflater.from(this@BookInfoActivity).inflate(R.layout.news_info_popup_window_layout, null)
        //创建并显示popWindow -360
        val mCustomPopWindow = CustomPopWindow.PopupWindowBuilder(this@BookInfoActivity)
            .setView(contentView)
            .create()
            .showAsDropDown(v, -20, -40)

        contentView.findViewById<AppCompatTextView>(R.id.share_tv).setOnClickListener {

            val image = UMImage(this, R.mipmap.ic_launcher)
            val web = UMWeb(/*mUrl*/"http://www.yancloud.red/Portal/Book/info/?id=$bookId") //切记切记 这里分享的链接必须是http开头
            web.title = mWebView.title//标题
            web.setThumb(image)  //缩略图
            if (bookBean != null) {

//                "你要分享内容的描述"//描述
                web.description = bookBean!!.content
            }else{

                web.description = bookBean!!.author
            }

            ShareAction(this).withMedia(image).withMedia(web)
                .setDisplayList(
                    SHARE_MEDIA.SINA,
                    SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE,
                    SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                    SHARE_MEDIA.MORE
                )
                .setCallback(umShareListener).open()
            mCustomPopWindow.dissmiss()
        }

        val collectTv = contentView.findViewById<AppCompatTextView>(R.id.collect_tv)
        if (state == Constants.CollectType.COLLECT) {

            val drawable = resources.getDrawable(R.mipmap.news_collect_ic)
            // 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
            collectTv.setCompoundDrawables(drawable, null, null, null)
        }

        collectTv.setOnClickListener {

            if (UserInfoShardPreference.instance.isLogin) {

                if (state == Constants.CollectType.COLLECT) {

                    RedCloudApis.getInstance().myCollectDelete(UserInfoShardPreference.instance.uid,id,object : Observer<ResponseBody> {
                        override fun onComplete() {
                        }

                        override fun onSubscribe(d: Disposable) {
                        }

                        override fun onNext(t: ResponseBody) {

                            val result = String(t.bytes())

                            if (!TextUtils.isEmpty(result)) {

                                val jsonObject = JSONObject.parseObject(result)

                                if (jsonObject.getString("code") == Constants.SYSTEM_OK) {

                                    val drawable = resources.getDrawable(R.mipmap.news_not_collect_ic)
                                    // 这一步必须要做,否则不会显示.
                                    drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                                    collectTv.setCompoundDrawables(drawable, null, null, null)

                                    ToastUtils.showToast(getString(R.string.cancel_collect))
                                    mCustomPopWindow.dissmiss()

                                    state = Constants.CollectType.NOT_COLLECT
                                }else{

                                    ToastUtils.showToast(jsonObject.getString("msg"))
                                }
                            }else{

                                ToastUtils.showToast(getString(R.string.cancel_collect_failure))
                            }
                        }

                        override fun onError(e: Throwable) {
                        }
                    })

                }else if(state == Constants.CollectType.NOT_COLLECT){

                    if (bookBean==null){

                        ToastUtils.toastNetErrorMsg()
                        return@setOnClickListener
                    }
                    RedCloudApis.getInstance().addFavorite(UserInfoShardPreference.instance.uid,bookBean!!.title,bookId,Constants.CollectModel.BOOK,object : Observer<ResponseBody> {
                        override fun onComplete() {
                        }

                        override fun onSubscribe(d: Disposable) {
                        }

                        override fun onNext(t: ResponseBody) {

                            val result = String(t.bytes())
                            if (!TextUtils.isEmpty(result)) {

                                val parseObject = JSONObject.parseObject(result)
                                if (parseObject.getString("code") == Constants.SYSTEM_OK) {

                                    val drawable = resources.getDrawable(R.mipmap.news_collect_ic)
                                    // 这一步必须要做,否则不会显示.
                                    drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                                    collectTv.setCompoundDrawables(drawable, null, null, null)

                                    ToastUtils.showToast(getString(R.string.collect_success))
                                    state = Constants.CollectType.COLLECT
                                }else{

                                    ToastUtils.showToast(getString(R.string.collect_failure))
                                }

                                mCustomPopWindow.dissmiss()
                            }
                        }

                        override fun onError(e: Throwable) {

                            ToastUtils.showToast(getString(R.string.collect_failure))
                            mCustomPopWindow.dissmiss()
                        }
                    })
                }
                //                    collectTv.setText(R.string.already_collect)
            }else{

                ToastUtils.showToast(R.string.not_login_prompt)
                startActivity(Intent(this,LoginActivity::class.java))
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        if (currentState != state) {

            EventBus.getDefault().post(MessageEvent(Constants.REFRESH_MY_COLLECT,""))
        }
    }

    private val umShareListener = object : UMShareListener {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        override fun onStart(platform: SHARE_MEDIA) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        override fun onResult(platform: SHARE_MEDIA) {

            ToastUtils.showToast("分享成功了")
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        override fun onError(platform: SHARE_MEDIA, t: Throwable) {

            ToastUtils.showToast("分享失败" + t.message)
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        override fun onCancel(platform: SHARE_MEDIA) {

        }
    }
}
